#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "malloc.h"
#if 1
#if defined(__APPLE__)
# include <sys/time.h>
# include <crt_externs.h>
# define environ (*_NSGetEnviron())
#endif /* __APPLE__ */
#endif

typedef void (*sd_malloc_handler_t)();

static char*  first_break = NULL;
static sd_malloc_handler_t handler  = NULL;

static void *
fixup_null_alloc (n)
    size_t n;
{
    void* p = 0;

#if HAVE_SBRK
    if (n == 0)
	p = (void*)PON_MALLOC_FUNCTION ((size_t) 1);

    if (p == 0) {
	extern char **environ;
	size_t allocated;

	if (first_break != NULL)
	    allocated = (char *) sbrk (0) - first_break;
	else
	    allocated = (char *) sbrk (0) - (char *) &environ;
	sd_error("\nCannot allocate %lu bytes after allocating %lu bytes\n",
		 (unsigned long) n, (unsigned long) allocated);
	
	if (handler) 
	    handler();
	else {
	    sd_error("\n\tMemory exhausted !! Aborting.\n");
	    abort();
	}
    }
#endif
    return p;
}

sd_malloc_handler_t
sd_malloc_set_handler(a_handler)
    sd_malloc_handler_t a_handler;
{
    sd_malloc_handler_t previous = handler;

    handler = a_handler;
    return previous;
}

/* Allocate N bytes of memory dynamically, with error checking.  */

void *
sd_malloc (n)
    size_t n;
{
    void *p;
    p = (void *)PON_MALLOC_FUNCTION (n);
    if (p == 0)
	p = fixup_null_alloc (n);
    return p;
}

/* Allocate memory for N elements of S bytes, with error checking.  */

void *
sd_calloc (n, s)
    size_t n, s;
{
    void *p;

    p = (void *)PON_CALLOC_FUNCTION(n, s);
    if (p == 0)
	p = fixup_null_alloc (n * s);
    return p;
}

/* Change the size of an allocated block of memory P to N bytes,
   with error checking.
   If P is NULL, run sd_malloc.  */

void *
sd_realloc (p, n)
    void *p;
    size_t n;
{
    if (p == 0)
	return sd_malloc (n);
    p = (void *)PON_REALLOC_FUNCTION(p, n);
    if (p == 0)
	p = fixup_null_alloc (n);
    return p;
}

/* Return a newly allocated copy of STRING.  */

char *
sd_strdup (string)
     const char *string;
{
  return strcpy (sd_malloc (strlen (string) + 1), string);
}

